package xin.nick.minicat;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;

/**
 * @author Nick
 * @date 2021/6/20
 * @description
 */
public class Response {

    private OutputStream outputStream;
    private MiniCatContent miniCatContent;

    public OutputStream getOutputStream() {
        return outputStream;
    }

    public void setOutputStream(OutputStream outputStream) {
        this.outputStream = outputStream;
    }

    public MiniCatContent getMiniCatContent() {
        return miniCatContent;
    }

    public void setMiniCatContent(MiniCatContent miniCatContent) {
        this.miniCatContent = miniCatContent;
    }

    public Response() {}

    public Response(OutputStream outputStream) {
        this.outputStream = outputStream;
    }

    /**
     * 输出静态资源
     * @param path
     */
    public void outputStatic(String path) throws IOException {

        String absoluteResourcePath = miniCatContent.getAppBase() + File.separator + path;

        File file = new File(absoluteResourcePath);

        if(file.exists() && file.isFile()) {
            // 读取文件输出
            StaticResourceUtil.outputStaticResource(new FileInputStream(file), outputStream);
        } else {
            output(HttpProtocolUtil.getHttpHeader404());
        }

    }

    /**
     * 输出字符串
     * @param content
     */
    public void output(String content) throws IOException {
        outputStream.write(content.getBytes());
    }
}
